import Scroll, { ScrollDirection, ScrollOptions } from "@/framework/layout/Scroll";
import { Handlers } from "./utils/Handlers";
import { DragEvent } from "./utils/EventEmitter";

export class ScrollView extends Scroll  {

  handlers: Handlers
  dragging: boolean
  clientX?: number
  clientY?: number

  constructor(options: ScrollOptions) {
    super(options)
    this.handlers = new Handlers({
      ...options,
      draggable: true,
      clickable: false
    })
    this.dragging = false
    this.clientX = null
    this.clientY = null
  }


  async load(): Promise<void> {
    super.load()
    this.handlers.addEventListener('dragStart', this.handleDrag.bind(this))
    this.handlers.addEventListener('dragEnd', this.handleDrag.bind(this))
    this.handlers.addEventListener('drag', this.handleDrag.bind(this))
  }

  async unload(): Promise<void> {
    this.handlers.removeEventListener('dragStart', this.handleDrag.bind(this))
    this.handlers.removeEventListener('dragEnd', this.handleDrag.bind(this))
    this.handlers.removeEventListener('drag', this.handleDrag.bind(this))
    super.unload()
  }

  handleDrag(dragEvt: DragEvent) {
    this.dragging = dragEvt.dragging
    var clientX = dragEvt.touch.clientX
    var clientY = dragEvt.touch.clientY
    
    if(this.scrollDirection === ScrollDirection.horizontal) {
      if(typeof this.clientX === 'number') {
        var dX = clientX - this.clientX
        this.scrollOffset = Math.max(0, this.scrollOffset + dX)
      }

      this.clientX = clientX
    } else if(this.scrollDirection === ScrollDirection.vertical) {
      if(typeof this.clientY === 'number') {
        var dY = clientY - this.clientY
        this.scrollOffset = Math.max(0, this.scrollOffset + dY)
      }
    }

    if(dragEvt.dragging === false) {
      this.clientX = null
      this.clientY = null
    }
  }
}